import React, { PropTypes } from 'react'
import {Select,InputNumber,Modal,Table,Steps,message,Button,Dropdown,Menu,Icon,Upload,Form,Input } from 'antd'
import styles from './ex.css'

const Step = Steps.Step;
const FormItem = Form.Item;
const Option = Select.Option;

const CustomizedForm = Form.create({
  onFieldsChange(props, changedFields) {
    props.onChange(changedFields);
  },
  mapPropsToFields(props) {
    return {
      username: {
        ...props.username
      },
      phone: {
        ...props.phone
      }
    };
  },
  onValuesChange(_, values) {
  	for (var i in _) {
  		for (var key in values) {
  			if(i == key){
  				_[i].value = values[key];
  			}
  		}
  	}
  	return _;
  },
})((props) => {
  const { getFieldDecorator,validateFieldsAndScroll } = props.form;
  return (
    <Form layout="inline">
      	<FormItem label="换货人姓名">
        	{getFieldDecorator('username', {
         		 rules: [
              {
                required: true,
                message: '请输入换货人姓名 '
              }
            ],validateTrigger: 'onBlur'
          })(<Input placeholder="换货人联系电话"/>)}
      	</FormItem>
      	<FormItem label="换货人联系电话">
        	{getFieldDecorator('phone', {
          		rules: [
              {
                required: true,
                message: '请输入合法的手机号码 ',
                pattern:'^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$',
                validator(rule, value, callback){
                  if(!/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(value)){
                  	callback('请输入合法的手机号码');
                    return;
                  }
                  callback();
                }
              }
            ],validateTrigger: 'onBlur'
        	})(<Input />)}
      	</FormItem>
    </Form>
  );
});


class ExModal extends React.Component {
	constructor (props) {
    	super(props);
    	this.state={
  			current: 0,
  			fields: props.fields,
    		dataSource: props.dataSource
		}
  }
	
	next(){
		// let reg = document.getElementById("applyCount").value
		// if(!/^\d+$/.test(reg)){
		// 	const modal  = Modal.error({
		// 		content:'只能输入整数'
		// 	})
		// 	return;
		// }

		this.setState({current: this.state.current + 1})
	}	
	prev(){
		this.setState({current: this.state.current - 1})
	}	
	onChange(value) {
	  console.log('changed', value);
	}

	onSubmit(){
		const phone = document.getElementById('phone').value;
		if(/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|17[0-9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(phone)){
	    this.props.onSubmit(this.state.dataSource,this.state.fields)  
		}else{
			const modal  = Modal.error({
				content:'请输入合法的手机号码'
			})
			// message.error('请输入合法的手机号码');
		}
	}
	
	handleFormChange = (changedFields) => {
	    this.setState({
	      	fields: { ...this.state.fields, ...changedFields },
	    });
	}
	
	handleChangeTableInput(text,row){
		// let reg = document.getElementById("applyCount").value
		// if(!/^\d+$/.test(text)){
		// 	const modal  = Modal.error({
		// 		content:'只能输入整数'
		// 	})
		// 	return;
		// }

		if(text<0){
			const modal  = Modal.error({
				content:'不能输入负数'
			})
			return;
		}
			if(!/^\d+$/.test(text)){
			const modal  = Modal.error({
				content:'只能输入整数'
			})
			return;
		}
		
		if(text > row.amount){
			 const modal = Modal.error({
           title: "超出可换货数量",
           okText: "确定"
        });
        return;
		}
		
		
		let dataSource = this.props.dataSource;
		for (let i = 0,len = dataSource.length; i < len; i++) {
			if(row.code == dataSource[i].code){
				dataSource[i].applyCount = text;
				this.setState({
					dataSource: dataSource
				})
			}
		}
		
	}
	
	handleChange(text,row) {
	  let dataSource = this.props.dataSource;
		for (let i = 0,len = dataSource.length; i < len; i++) {
			if(row.code == dataSource[i].code){
				dataSource[i].exreson = text;
				this.setState({
					dataSource: dataSource
				})
			}
		}
		console.log(this.state.dataSource)
	}

	render(){
    const { dataSource,fields } = this.props; 
		const modalOpts = {
			title: '',
			visible: this.props.visible,
			onOk: function(){
				console.log(111);
			},
			onCancel: this.props.onCancel,
			cancelText:'关闭',
			maskClosable:false,
			closable:true,
			// wrapClassName: 'vertical-center-modal'
		};

				
		const props = {
		    name: 'file',
		    action: '//jsonplaceholder.typicode.com/posts/',
		    headers: {
		      authorization: 'authorization-text',
		    },
			 onChange(info) {
			    if (info.file.status !== 'uploading') {
			        console.log(info.file, info.fileList);
			    }
			    if (info.file.status === 'done') {
			        message.success(`${info.file.name} file uploaded successfully`);
			    } else if (info.file.status === 'error') {
			        message.error(`${info.file.name} file upload failed.`);
			    }
		    },
		};

		const columns = [{
		  title: '商品名称',
		  dataIndex: 'name',
		  key: 'name',
		}, {
		  title: '温区',
		  dataIndex: 'areaName',
		  key: 'areaName',
		}, {
		  title: '商品规格',
		  dataIndex: 'standard',
		  key: 'standard',
		}, {
		  title: '可换货数',
		  dataIndex: 'amount',
		  key: 'amount',
		}, {
		  title: '申请客服换货数',
		  dataIndex: 'applyCount',
		  key: 'applyCount',
		  render:(text,recode)=>{
		  	var num = text == undefined ? 0 : text;
		  	return(
		  	    <InputNumber id="applyCount" min={0} defaultValue={0} max={recode.amount} onChange={(value)=>this.handleChangeTableInput(value,recode)} />
		  	)
		  }
		}, {
		  title: '换货理由',
		  dataIndex: 'exreson',
		  key: 'exreson',
		  render:(text,recode)=>{
		  		return(
				    <Select defaultValue="不填" style={{ width: 120 }} onChange={(value)=>this.handleChange(value,recode)}>
				      <Option value="品质问题">品质问题</Option>
				      <Option value="破损">破损</Option>
				      <Option value="生产日期过长">生产日期过长</Option>
				      <Option value="送错货品">送错货品</Option>
				      <Option value="其他">其他</Option>
				    </Select>
		  		)
		  	}
		}
		// , {
		//   title: '上传图片',
		//   dataIndex: 'uploadimg',
		//   key: 'uploadimg',
		//   render:(text,recode)=>{
		//   	return(
		//   		<Upload {...props}>
		// 		    <Button>
		// 		      图片上传
		// 		      <Icon type="upload" /> 
		// 		    </Button>
		// 	  </Upload>
		//   	)
		//   }
		// }
		];

		const columns2 = [{
		  title: '商品名称',
		  dataIndex: 'name',
		  key: 'name',
		}, {
		  title: '温区',
		  dataIndex: 'areaName',
		  key: 'areaName',
		}, {
		  title: '商品规格',
		  dataIndex: 'standard',
		  key: 'standard',
		}, {
		  title: '可换货数',
		  dataIndex: 'amount',
		  key: 'amount'
		}, {
		  title: '客服换货数',
		  dataIndex: 'applyCount',
		  key: 'applyCount',
		  render:(text,recode)=>{
		  	var p = text == undefined ? 0 : text;
		  	return(
		  		<p>{p}</p>
		  		)
		  	}
		}, {
		  title: '换货理由',
		  dataIndex: 'exreson',
		  key: 'exreson',
		  render:(text,recode)=>{
		  	var p = text || '不填';
		  	return(
		  		<p>{p}</p>
		  		)
		  	}
		}
		// , {
		//   title: '反馈图片',
		//   dataIndex: 'uploadimg',
		//   key: 'uploadimg'
		// }
		];
		
		const steps = [{
		  title: '客服换货',
		  content: <Table dataSource={dataSource} columns={columns} rowKey={record => record.id} pagination={false}/>
		},{
		  title: '确认换货操作',
		  content: <Table dataSource={dataSource} columns={columns2} rowKey={record => record.id} pagination={false}/>
		},{
		  title: '确认换货人联系方式',
		  content: <CustomizedForm {...fields} onChange={this.handleFormChange} pagination={false} />
		}];
		
		const { current } = this.state;
		
		
		return(
			<Modal {...modalOpts} className={styles.antModal} footer={null}>
      		<div className='steps-box' style={{marginTop: '15px'}}>	      		
    			<Steps current={current}>
		          	{steps.map(item => <Step key={item.title} title={item.title} />)}
		        </Steps>
      		
	        <div className="steps-content" style={{marginTop:20}}>{steps[current].content}</div>
	        
	        <div className="steps-action" style={{textAlign:'right',marginTop: '15px'}}>
		        {
		            current === steps.length - 1 && <Button type="primary" onClick={() => this.onSubmit()}>确认并保存</Button>
		        }
		     {   // {
		     		        //     current > 0 && <Button style={{ marginLeft: 8 }} onClick={() => this.prev()}>返回</Button>
		     		        // }
		     	}
		        {
		            current < steps.length - 1 && <Button style={{ marginLeft: 8 }} type="primary" onClick={() => this.next()}>下一步</Button>
		        }
	        </div>
      	</div>
		   </Modal>
		)
	}
};

ExModal.propTypes = {
	visible: PropTypes.any,
	item: PropTypes.object,
	onOk: PropTypes.func,
	onCancel: PropTypes.func
};

export default ExModal